import { createRouter, createWebHistory } from 'vue-router'
import { type RouteLocationNormalized } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import MicroAppContainer from '../views/MicroAppContainer.vue'
import { useMicroAppsStore } from '@/stores/microApps'
import { microApps } from '@/micro/microApps'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        title: '首页',
      },
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: {
        title: '关于',
      },
    },
    // 显式定义已知路由后，最后匹配微应用
    {
      path: '/:microApp(.*)*',
      name: 'microApp',
      component: MicroAppContainer,
      meta: {
        title: '微应用',
      },
      beforeEnter: (to) => {
        // 排除已知路径
        const excludedPaths = ['/subapp', '/Investment']
        if (excludedPaths.some((path) => to.path.startsWith(path))) {
          return true // 继续原有导航
        }
        return true
      },
    },
  ],
})

// 路由守卫，处理微应用状态
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  const microAppsStore = useMicroAppsStore()

  // 查找匹配的微应用
  const matchedApp = microApps.find((app) => {
    const activeRule =
      typeof app.activeRule === 'string'
        ? app.activeRule
        : (app.activeRule as (location: Location) => boolean)(window.location)

    if (typeof activeRule === 'string') {
      return to.path.startsWith(activeRule)
    }
    return false
  })

  // 更新当前微应用状态
  if (matchedApp) {
    microAppsStore.setCurrentApp(matchedApp.name)
    // 更新页面标题
    document.title = `${matchedApp.name} - Rim.WebMS`
  } else {
    microAppsStore.setCurrentApp('')
    // 设置默认标题
    document.title = to.meta.title ? `${to.meta.title} - Rim.WebMS` : 'Rim.WebMS'
  }

  return true
})

// 路由错误处理
router.onError((error) => {
  const microAppsStore = useMicroAppsStore()
  microAppsStore.setError(error)
  console.error('路由错误:', error)
})

export default router
